package com.sky.service.impl;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;

import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.sky.entity.Orders.*;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        AddressBook byId = addressBookMapper.getById(orders.getAddressBookId());

        Long currentId = BaseContext.getCurrentId();
        orders.setUserId(currentId);
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(currentId);
        List<ShoppingCart> select = shoppingCartMapper.select(shoppingCart);
        ShoppingCart shoppingCart1 = select.get(0);
        //判断购物车和地址是否为空
        if (shoppingCart1 == null) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        if (byId == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        String provinceName = byId.getProvinceName();
        String cityName = byId.getCityName();
        String districtName = byId.getDistrictName();
        String detail = byId.getDetail();
        String address = provinceName + cityName + districtName + detail;
        orders.setAddress(address);
        orders.setPhone(byId.getPhone());

        orders.setConsignee(byId.getConsignee());
        //向订单表中插入数据
        orderMapper.insert(orders);
        //向订单明细表中插入数据


        List<OrderDetail> list = new ArrayList<>();
        for (ShoppingCart cart : select) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            list.add(orderDetail);
        }

        orderDetailMapper.insert(list);

//清空购物车
//        TODO 有错误
        shoppingCartMapper.clean(orders.getUserId());


        Long id = orders.getId();
        String number = orders.getNumber();
        BigDecimal amount = orders.getAmount();
        LocalDateTime orderTime = orders.getOrderTime();
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO(id, number, amount, orderTime);
        return orderSubmitVO;


//        int tablewareNumber = orders.getTablewareNumber();
//        BigDecimal tableware= BigDecimal.valueOf(tablewareNumber*6);
//        BigDecimal packAmount = BigDecimal.valueOf(orders.getPackAmount());
//
//
//        BigDecimal amount = shoppingCart1.getAmount();
//        BigDecimal bigDecimal=tableware.add(packAmount).add(amount);
//
//        orders.setAmount(bigDecimal);


    }

    @Override
    public PageResult selectPage(int pageNum, int pageSize, Integer status) {

        PageHelper.startPage(pageNum, pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        Long currentId = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(currentId);
        ordersPageQueryDTO.setStatus(status);

        Page<Orders> page = orderMapper.selectPage(ordersPageQueryDTO);


        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.selectBy(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);


    }

    @Override
    public OrderVO selectOD(Long id) {


        Orders orders = orderMapper.selectById(id);

        // String string = orders.toString();
        List<OrderDetail> orderDetailList = orderDetailMapper.selectBy(id);
        OrderVO orderVO = new OrderVO();

        BeanUtils.copyProperties(orders, orderVO);
        // orderVO.setOrderDishes(string);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }


    @Override
    public void cancel(Long id) {


        Orders orders = orderMapper.selectById(id);

        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Integer status = orders.getStatus();
        if (status <= 2) {
            if (status.equals(TO_BE_CONFIRMED)) {
                log.info("给用户退款");
                orders.setPayStatus(REFUND);
            }
            orders.setCancelTime(LocalDateTime.now());
            orders.setStatus(CANCELLED);
            orders.setCancelReason("用户取消");
            orderMapper.update(orders);


        }

        if (status.equals(CONFIRMED) && status.equals(DELIVERY_IN_PROGRESS)) {
            log.info("请给商家电话联系");
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        }

    }

    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.selectById(id);

        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "订单号" + orders.getNumber());

        //将json的数据转换成json格式的字符串
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);

    }

    @Override
    public PageResult selectAPage(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.selectPage(ordersPageQueryDTO);
        List<Orders> results = page.getResult();

        List<OrderVO> list = new ArrayList();


        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && results.size() > 0) {
            for (Orders result : results) {
                OrderVO orderVO = getOrderVO(result);
                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);


    }

    private OrderVO getOrderVO(Orders result) {
        //  Long orderId = result.getId();// 订单id
        // 查询订单明细
        List<OrderDetail> orderDetailList = orderDetailMapper.selectBy(result.getId());
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(result, orderVO);
        orderVO.setOrderDetailList(orderDetailList);


        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        String orderDishes = String.join("", orderDishList);

        // orderVO.setOrderDetailList(orderDetails);
        orderVO.setOrderDishes(orderDishes);
        return orderVO;
    }

    @Override
    public OrderStatisticsVO selectStatistics() {
        Integer three = orderMapper.selectStatistics(CONFIRMED);
        Integer four = orderMapper.selectStatistics(DELIVERY_IN_PROGRESS);
        Integer two = orderMapper.selectStatistics(TO_BE_CONFIRMED);

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(three);
        orderStatisticsVO.setDeliveryInProgress(four);
        orderStatisticsVO.setToBeConfirmed(two);
        return orderStatisticsVO;

    }

    @Override
    public OrderVO selectDetail(Long id) {
        Orders orders = orderMapper.selectById(id);
        OrderVO orderVO = getOrderVO(orders);
        return orderVO;

    }

    @Override
    public void confirm(Long id) {
        Orders orders = orderMapper.selectById(Long.valueOf(id));
        orders.setStatus(CONFIRMED);
        orderMapper.update(orders);

    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {


        Orders orders = orderMapper.selectById(ordersRejectionDTO.getId());
        Integer status = orders.getStatus();
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (status == TO_BE_CONFIRMED) {
            orders.setCancelReason(ordersRejectionDTO.getRejectionReason());
            //给用户退款
            orders.setPayStatus(REFUND);
            orders.setStatus(CANCELLED);

            orders.setCancelTime(LocalDateTime.now());


            orderMapper.update(orders);
        }


    }

    @Override
    public void cancelA(OrdersCancelDTO ordersCancelDTO) {

        Orders orders = orderMapper.selectById(ordersCancelDTO.getId());
        Integer status = orders.getStatus();
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (status < 4) {
            orders.setCancelReason(ordersCancelDTO.getCancelReason());
            //给用户退款
            orders.setPayStatus(REFUND);
            orders.setStatus(CANCELLED);

            orders.setCancelTime(LocalDateTime.now());


            orderMapper.update(orders);
        }


    }

    @Override
    public void complete(Long id) {
        Orders orders = orderMapper.selectById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }


        orders.setStatus(COMPLETED);
        orderMapper.update(orders);

    }

    @Override
    public void delivery(Long id) {
        Orders orders = orderMapper.selectById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        if (orders.getStatus().equals(CONFIRMED)) {
            orders.setStatus(DELIVERY_IN_PROGRESS);
            orderMapper.update(orders);
        }

    }


    @Override
    public void repetiton(Long id) {
        Long currentId = BaseContext.getCurrentId();

        List<OrderDetail> orderDetailList = orderDetailMapper.selectBy(id);

        List<ShoppingCart> shoppingCarts = new ArrayList<>();

        for (OrderDetail orderDetail : orderDetailList) {
//            OrderDetail orderDetail = new OrderDetail();
//            BeanUtils.copyProperties(OD, orderDetail);
//            orderDetail.setOrderId(currentId);
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(currentId);
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCarts.add(shoppingCart);

        }
        shoppingCartMapper.insert2(shoppingCarts);


    }

    @Override
    public void pay(OrdersPaymentDTO ordersPaymentDTO) {
        Orders orders = new Orders();
        Long userId = BaseContext.getCurrentId();
        BeanUtils.copyProperties(ordersPaymentDTO, orders);

        orders.setNumber(ordersPaymentDTO.getOrderNumber());
        orders.setUserId(userId);
        orders.setStatus(TO_BE_CONFIRMED);
        orders.setPayStatus(PAID);
// 数据库
        Orders orders1 = orderMapper.selectByNumberAndByUserID(ordersPaymentDTO.getOrderNumber(), userId);

        orders.setId(orders1.getId());
        orderMapper.update(orders);


        //支付成功后向客户端推送数据
        Map map = new HashMap<>();
        map.put("type", 1);
        map.put("openId", orders1.getId());
        map.put("content", "订单号" + orders.getNumber());
        String jsonString = JSON.toJSONString(map);

        webSocketServer.sendToAllClient(jsonString);
    }


}
